package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController(value = "userAddressBook")
@RequestMapping("/user/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    // 新增地址
    @ApiOperation("新增地址")
    @PostMapping
    public Result insert(@RequestBody AddressBook addressBook) {
        addressBookService.insert(addressBook);
        return Result.success();
    }

    // 查询登录用户所有地址
    @ApiOperation("查询登录用户所有地址")
    @GetMapping("/list")
    public Result list() {
        log.info("userId:",BaseContext.getCurrentId());
        List<AddressBook> addressBook = addressBookService.list();
        return Result.success(addressBook);
    }

    // 查询默认地址
    @ApiOperation("查询默认地址")
    @GetMapping("/default")
    public Result findDefault() {
        List<AddressBook> addressBooks = addressBookService.findDefault();
        if (addressBooks != null && addressBooks.size() == 1) {
            return Result.success(addressBooks.get(0));
        }
        return Result.error("没有查询到默认地址");
    }

    // 根据id修改地址
    @ApiOperation("根据id修改地址")
    @PutMapping
    public Result update(@RequestBody AddressBook addressBook) {
        addressBookService.update(addressBook);
        return Result.success();
    }

    // 根据id删除地址
    @ApiOperation("根据id删除地址")
    @DeleteMapping
    public Result deleteById(Long id) {
        addressBookService.deleteById(id);
        return Result.success();
    }

    // 根据id查询地址
    @ApiOperation("/根据id查询地址")
    @GetMapping("/{id}")
    public Result findById(@PathVariable Long id) {
        AddressBook addressBook = addressBookService.findById(id);
        return Result.success(addressBook);
    }

    // 设置默认地址
    @ApiOperation("设置默认地址")
    @PutMapping("/default")
    public Result updateDefault(@RequestBody AddressBook addressBook) {
        addressBookService.updateDefault(addressBook);
        return Result.success();
    }

}























